package com.business.user.utils;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.business.common.enums.Order;
import com.business.common.utils.StrKit;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 默认分页
 * 
 *   
 * @author chenjiehong
 * @date 2017年10月31日
 * @since 1.0
 */
public class PageFactory<T> {
    private static final int DEFAULT_SIZE = 20;

	public Page<T> defaultPage(JSONObject paramJson) {
		int limit = DEFAULT_SIZE;
		int current = 1;
		if (!StrKit.isEmpty(paramJson.getString("size"))) {
			limit = paramJson.getIntValue("size");
			current = paramJson.getIntValue("page");
		} 

		String sort = paramJson.getString("sort");
		String order = paramJson.getString("order");
		if (StrKit.isEmpty(sort)) {
			Page<T> page = new Page<>(current, limit);
			page.setOpenSort(false);
			return page;
		} else {
			Page<T> page = new Page<>(current, limit, sort);
			if (Order.ASC.getDes().equals(order)) {
				page.setAsc(true);
			} else {
				page.setAsc(false);
			}
			return page;
		}
	}
	
	public Page<T> defaultPage() {
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = attributes.getRequest();
		int size = 12;
		int current = 0;
		if (!StringUtils.isEmpty(request.getParameter("size"))) {
			size = Integer.valueOf(request.getParameter("size"));
			current = Integer.valueOf(request.getParameter("page"));
		} else {
			size = 60000;
			current = 0;
		}
		String sort = request.getParameter("sort");
		String order = request.getParameter("order");
		if (StringUtils.isEmpty(sort)) {
			Page<T> page = new Page<>(current, size);
			page.setOpenSort(false);
			return page;
		} else {
			Page<T> page = new Page<>(current, size, sort);
			if (Order.ASC.getDes().equals(order)) {
				page.setAsc(true);
			} else {
				page.setAsc(false);
			}
			return page;
		}
	}
		
}
